package cn.modfun.web.core.hanlder;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.modfun.common.lang.StringUtils;
import cn.modfun.web.core.annotation.Parameter;
import cn.modfun.web.core.annotation.Parameter.FilterMode;
import cn.modfun.web.core.annotation.Parameter.TrimMode;
import cn.modfun.web.core.annotation.RequestParameter;
import cn.modfun.web.core.servlet.ParameterHttpServletRequestWrapper;
import com.jfinal.core.Action;
import com.jfinal.core.JFinal;
import com.jfinal.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ParameterFilterHandler extends Handler {

	Setting setting = null;
	
	public ParameterFilterHandler(Setting setting){
		this.setting = setting;
	}
	
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		//request = new ParameterHttpServletRequestWrapper(request);
		boolean is_filter = true;
		if(setting.getStrings("white_list")!=null){
			if("".equals(target)){
				is_filter = false;
			}
			for(String uri : setting.getStrings("white_list")){
				if(StrUtil.isNotBlank(uri)){
					if(target.indexOf(uri)==0){
						is_filter = false;
					}
				}
			}
		}
		
		if(is_filter){
			String[] urlPara = {null};
			Action action = JFinal.me().getAction(target, urlPara);
			if(action != null){
				/* 获得到目标方法 */
				Method method = action.getMethod();
				RequestParameter parameters = method.getAnnotation(RequestParameter.class);
				/* 获取参数对应的xss模式 */
				Map<String,FilterMode> filterPolicy = new HashMap<String,FilterMode>();
				Map<String,TrimMode> trimPolicy = new HashMap<String,TrimMode>();
				/* 先处理实体类 */
				if(parameters!=null){
					/* 处理自定义 */
					for(Parameter parameter : parameters.value()){
						filterPolicy.put(StringUtils.isBlank(parameter.key())?parameter.name():parameter.key(), parameter.filterMode());
						trimPolicy.put(StringUtils.isBlank(parameter.key())?parameter.name():parameter.key(), parameter.trimMode());
					}
				}
				request = new ParameterHttpServletRequestWrapper(request,filterPolicy,trimPolicy);  
			}
		}
		next.handle(target, request, response, isHandled);
	}

}
